package com.lindroy.androidplayer.ui.webview

import android.content.Context
import android.view.Menu
import android.view.MenuItem
import android.view.Window
import android.widget.FrameLayout
import androidx.activity.viewModels
import com.just.agentweb.AgentWeb
import com.lindroid.androidutilskt.statics.IntentUtil
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.base.BaseActivity
import com.lindroy.androidplayer.base.eventViewModel
import com.lindroy.androidplayer.extensions.globalLoginInfo
import com.lindroy.androidplayer.extensions.judgeLogin
import com.lindroy.androidplayer.extensions.no
import com.lindroy.androidplayer.extensions.yes
import com.lindroy.androidplayer.logic.model.bean.CollectBus
import com.lindroy.androidplayer.logic.model.bean.ContentBean
import com.lindroy.androidplayer.viewmodel.CollectViewModel
import com.lindroy.lib_utils.extensions.extraParcelable
import com.lindroy.lib_utils.extensions.hideKeyboard
import com.lindroy.lib_utils.extensions.launchActivity
import com.lindroy.lib_utils.extensions.shortToast
import com.orhanobut.logger.Logger
import com.youngfeng.snake.annotations.EnableDragToClose
import kotlinx.android.synthetic.main.activity_content.*
import java.lang.reflect.Method

/**
 * @author Lin
 * @date 2021/4/24
 * @function WebView页面
 * @Description
 */
private const val KEY_CONTENT = "content"

@EnableDragToClose
class ContentActivity(override val layoutId: Int = R.layout.activity_content) : BaseActivity() {

    private val contentBean by extraParcelable(KEY_CONTENT, ContentBean())

    private val collectedViewModel: CollectViewModel by viewModels()

    private val preWeb: AgentWeb.PreAgentWeb by lazy {
        AgentWeb.with(this)
            .setAgentWebParent(flContent, FrameLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .createAgentWeb()
            .ready()
    }

    private lateinit var agentWeb: AgentWeb

    override fun initView() {
        initToolBar(contentBean.title) {
            flContent.hideKeyboard()
            if (agentWeb.webCreator.webView.canGoBack()) {
                agentWeb.webCreator.webView.goBack()
            } else {
                finish()
            }
        }
        addLoadingObserve(collectedViewModel)
    }

    override fun initData() {
        agentWeb = preWeb.go(contentBean.url)
    }

    override fun initListener() {

        collectedViewModel.collectState.observe(this) {
            it.success.yes {
                contentBean.collected = it.collect
                eventViewModel.collectEvent.value = CollectBus(it.id, it.collect, it.originId)
            }
        }
        eventViewModel.collectEvent.observeInActivity(this) { collectBus ->
            Logger.d("Content，id=${collectBus.id}，collect=${collectBus.collect}")
            window.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL)
            invalidateOptionsMenu()
        }
    }

    override fun initClick() {

    }

    override fun onPause() {
        agentWeb.webLifeCycle?.onPause()
        super.onPause()
    }

    override fun onResume() {
        agentWeb.webLifeCycle?.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        agentWeb.webLifeCycle?.onDestroy()
        super.onDestroy()
    }

    override fun onBackPressed() {
        if (agentWeb.webCreator.webView.canGoBack()) {
            agentWeb.webCreator.webView.goBack()
        } else {
            super.onBackPressed()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.web_content_menu, menu)
        menu.findItem(R.id.web_collect)?.setIcon(contentBean.collectedIconId)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.web_collect -> {
                //TODO(首页轮播图的收藏应该如何处理呢？)
                collectedViewModel.toggleCollectListArticle(contentBean.collected, contentBean.id)
                /*if(contentBean.collectedType == ContentBean.TYPE_ARTICLE){
                    collectedViewModel.toggleCollectListArticle(contentBean.collected,contentBean.id)
                }else{

                }*/
            }
            R.id.web_share -> {
                IntentUtil.share(
                    this,
                    contentBean.title,
                    contentBean.url,
                    getString(R.string.share_title)
                )
            }
            R.id.web_browser -> {
                IntentUtil.launchBrowse(this, contentBean.url) {
                    if (it.not()) {
                        shortToast(getString(R.string.launch_browser_first))
                    }
                }
            }
        }
        return true
    }

    // 让菜单同时显示图标和文字
    override fun onMenuOpened(featureId: Int, menu: Menu?): Boolean {
        if (menu != null) {
            if (menu.javaClass.simpleName.equals("MenuBuilder", ignoreCase = true)) {
                try {
                    val method: Method = menu.javaClass.getDeclaredMethod(
                        "setOptionalIconsVisible",
                        java.lang.Boolean.TYPE
                    )
                    method.isAccessible = true
                    method.invoke(menu, true)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        return super.onMenuOpened(featureId, menu)
    }

    companion object {
        fun start(
            context: Context,
            id: Int,
            url: String,
            title: String,
            collected: Boolean,
            collectedType: Int = ContentBean.TYPE_ARTICLE
        ) {
            context.launchActivity<ContentActivity>(
                KEY_CONTENT to ContentBean(
                    id,
                    url,
                    title,
                    collected,
                    collectedType
                )
            )
        }
    }
}